package com.nice.nice201110.service;

import com.nice.nice201110.entity.*;
import com.nice.nice201110.mapper.TBasePictureMapper;
import com.nice.nice201110.mapper.TDeliveryDelMapper;
import com.nice.nice201110.mapper.TLogMapper;
import com.nice.nice201110.mapper.TMedicationTreatmentMapper;
import com.nice.nice201110.utils.NiceEnum;
import com.nice.nice201110.utils.NiceTableEnum;
import com.nice.nice201110.vo.BaseVo;
import com.nice.nice201110.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class TMedicationTreatmentService {

    @Autowired
    TMedicationTreatmentMapper tMedicationTreatmentMapper;

    @Autowired
    TBasePictureMapper tBasePictureMapper;

    @Autowired
    TDeliveryDelMapper tDeliveryDelMapper;

    @Autowired
    TLogMapper tLogMapper;

    @Autowired
    private PlatformTransactionManager ransactionManager;

    private TLog tLog = new TLog();
    /** 查询数据 */
    public List<TMedicationTreatment> getList(BaseVo baseVo){
        return tMedicationTreatmentMapper.selectByPrimaryKeys(baseVo);
    }
    /** 单一查询  */
    public TMedicationTreatment getOne(UserVo userVo, Integer id){
        TMedicationTreatment tMedicationTreatment = tMedicationTreatmentMapper.selectByPrimaryKey(id);
        if(tMedicationTreatment!=null){
            tLog.setDate(new Date());
            tLog.setType(3);  //操作类型（新增0，修改1，删除2,查询3）
            tLog.setDocid(tMedicationTreatment.getId());
            tLog.setUsername(userVo.getName());
            tLog.setUserid(Integer.valueOf(userVo.getId()));
            tLog.setTtable(NiceTableEnum.form_medication_treatment);
            tLog.setRemark("查看疾病及用药处理信息:"+tMedicationTreatment.toString());
            tLogMapper.insertSelective(tLog);
        }
        return tMedicationTreatment;
    }
    /** 用药操作 */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public Boolean inserttMedicationTreatment(UserVo userVo,TMedicationTreatment tMedicationTreatment){
        try {
            Integer tMedicationTreatmentNum = tMedicationTreatmentMapper.insertSelective(tMedicationTreatment);
            if(tMedicationTreatmentNum>0){
                tLog.setDate(new Date());
                tLog.setType(0);  //操作类型（新增0，修改1，删除2）
                tLog.setDocid(tMedicationTreatment.getId());
                tLog.setUsername(userVo.getName());
                tLog.setUserid(Integer.valueOf(userVo.getId()));
                tLog.setTtable(NiceTableEnum.form_medication_treatment);
                tLog.setRemark("新增用药信息:"+tMedicationTreatment.toString());
                tLogMapper.insertSelective(tLog);
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
            Integer pictureid = tMedicationTreatment.getPictureid(); //药id
            if(pictureid!=null&&pictureid>0) {
                BigDecimal pictureNum = tMedicationTreatment.getPicturenum(); //获取用药数量
                TBasePicture tBasePicture = tBasePictureMapper.selectByPrimaryKey(pictureid);
                if (tBasePicture == null) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                BigDecimal pictureNumOld = tBasePicture.getNumber(); //获药的数量
                BigDecimal pictureNumNew = pictureNumOld.subtract(pictureNum); //获药的新数量
                tBasePicture.setNumber(pictureNumNew);  //插入数量
                Integer tBasePictureNum = tBasePictureMapper.updateByPrimaryKeySelective(tBasePicture);
                if(tBasePictureNum>0){
                    String PictureName = tBasePicture.getName();
                    tLog.setDate(new Date());
                    tLog.setType(1);  //操作类型（新增0，修改1，删除2）
                    tLog.setDocid(tBasePicture.getId());
                    tLog.setUsername(userVo.getName());
                    tLog.setUserid(Integer.valueOf(userVo.getId()));
                    tLog.setTtable(NiceTableEnum.form_base_capital);
                    tLog.setRemark("系统自动减少["+PictureName+"]药品:"+pictureNum.toString());
                    tLogMapper.insertSelective(tLog);
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                String Informationids = tMedicationTreatment.getInformationids();  //用药（基本信息IDS）
                if(Informationids!=null&&Informationids.trim().length()>0){
                    String InformationidArr [] = Informationids.split(",");
                    Integer InformationSize = InformationidArr.length;
                    Double StorageQuantityDouble = pictureNum.doubleValue();  // 用药数量
                    Double InformationNum = StorageQuantityDouble/InformationSize;
                    BigDecimal BInformationNum = BigDecimal.valueOf(InformationNum); //单个信息的使用数量
                    BigDecimal Price = tBasePicture.getPrice();  //获取药品单价
                    BigDecimal pPrice = BInformationNum.multiply(Price);  //单价＊数量
                    for(String Informationid:InformationidArr){
                        TDeliveryDel tDeliveryDel = new TDeliveryDel();
                        tDeliveryDel.setType(NiceEnum.del_use_yao);
                        tDeliveryDel.setAmountSpent(pPrice);  // 花费金额
                        tDeliveryDel.setDeliveryTime(new Date());
                        tDeliveryDel.setInformationid(Informationid);//基本信息id
                        tDeliveryDel.setParentid(tMedicationTreatment.getId());   //父类id
                        tDeliveryDel.setName(tBasePicture.getId());   // 药品id
                        tDeliveryDel.setNumber(BInformationNum);  //数量
                        int tDeliveryDelInsertNum = tDeliveryDelMapper.insertSelective(tDeliveryDel);
                        if(tDeliveryDelInsertNum<=0){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return false;
                        }
                    }
                }
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }
    /** 用药操作退回 */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public Boolean deletetMedicationTreatment(UserVo userVo,Integer id){
        try {
            TMedicationTreatment tMedicationTreatment = tMedicationTreatmentMapper.selectByPrimaryKey(id);
            if(tMedicationTreatment==null){
                return false;
            }
            Integer tMedicationTreatmentNum = tMedicationTreatmentMapper.deleteByPrimaryKey(id);
            if(tMedicationTreatmentNum>0){
                tLog.setDate(new Date());
                tLog.setType(2);  //操作类型（新增0，修改1，删除2）
                tLog.setDocid(tMedicationTreatment.getId());
                tLog.setUsername(userVo.getName());
                tLog.setUserid(Integer.valueOf(userVo.getId()));
                tLog.setTtable(NiceTableEnum.form_medication_treatment);
                tLog.setRemark("删除用药信息:"+tMedicationTreatment.toString());
                tLogMapper.insertSelective(tLog);
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
            Integer pictureid = tMedicationTreatment.getPictureid(); //药id
            if(pictureid!=null&&pictureid>0) {
                BigDecimal pictureNum = tMedicationTreatment.getPicturenum(); //获取用药数量
                TBasePicture tBasePicture = tBasePictureMapper.selectByPrimaryKey(pictureid);
                if (tBasePicture == null) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                BigDecimal pictureNumOld = tBasePicture.getNumber(); //获药的数量
                BigDecimal pictureNumNew = pictureNumOld.add(pictureNum); //获药的新数量
                tBasePicture.setNumber(pictureNumNew);  //插入数量
                Integer tBasePictureNum = tBasePictureMapper.updateByPrimaryKeySelective(tBasePicture);
                if(tBasePictureNum>0){
                    String PictureName = tBasePicture.getName();
                    tLog.setDate(new Date());
                    tLog.setType(1);  //操作类型（新增0，修改1，删除2）
                    tLog.setDocid(tBasePicture.getId());
                    tLog.setUsername(userVo.getName());
                    tLog.setUserid(Integer.valueOf(userVo.getId()));
                    tLog.setTtable(NiceTableEnum.form_base_capital);
                    tLog.setRemark("系统自动回滚["+PictureName+"]药品:"+pictureNum.toString());
                    tLogMapper.insertSelective(tLog);
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                int tDeliveryDelInsertNum = tDeliveryDelMapper.deleteByParentId(id,NiceEnum.del_use_yao);
                if(tDeliveryDelInsertNum<=0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }
}
